Skip to content

fix bug in normalize#1

Open
suborofu wants to merge 1 commit into
evvaletov:masterfrom
suborofu:master
Open

fix bug in normalize#1
suborofu wants to merge 1 commit into
evvaletov:masterfrom
suborofu:master

Conversation

@suborofu
Copy link
Copy Markdown

@suborofu suborofu commented May 27, 2026

Summary by CodeRabbit

  • Bug Fixes
    • Fixed vector normalization to handle zero-length vectors gracefully, preventing errors during edge case calculations.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 27, 2026

📝 Walkthrough

Walkthrough

The normalize() function in stepfg/_geometry.py is now guarded against zero-length vectors. When the computed magnitude is zero, the function returns a zero vector instead of proceeding with division, preventing arithmetic errors.

Changes

Normalize function zero-guard

Layer / File(s) Summary
Zero-magnitude guard in normalize
stepfg/_geometry.py
normalize() adds an early conditional that returns a zero vector when magnitude is zero, preventing division-by-zero errors.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 A vector once tried to normalize,
But zero length made math a crisis,
Now guards check the length with care,
Returning zeros when none's there,
Safe division, bugs despise us! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix bug in normalize' directly relates to the main change: adding a guard against zero-length vectors in the normalize() function to prevent division-by-zero.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
stepfg/_geometry.py (1)

14-14: ⚡ Quick win

Consider using epsilon comparison for numerical stability.

The exact comparison magnitude == 0 only catches vectors with all components exactly zero. Near-zero vectors from floating-point arithmetic may have very small but non-zero magnitudes, which could lead to numerical instability when dividing. Standard practice in numerical computing is to use an epsilon threshold.

💡 Suggested improvement
-    if magnitude == 0:  # in some cases vector_in has zeros only
+    if magnitude < 1e-10:  # guard against zero or near-zero vectors
         return [0 for _ in vector_in]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@stepfg/_geometry.py` at line 14, Replace the exact zero check on magnitude
with an epsilon comparison to avoid dividing by near-zero floats: instead of if
magnitude == 0 use if abs(magnitude) < EPS where EPS is a small constant (e.g.
1e-12 or numpy.finfo(float).eps) defined near the top of the module; when the
magnitude is below EPS handle the near-zero vector_in the same way you currently
handle exact zeros (return a zero vector or skip normalization) to preserve
numerical stability. Ensure you reference the same symbols (magnitude,
vector_in) and add an import or constant definition for EPS if not already
present.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@stepfg/_geometry.py`:
- Around line 14-15: The normalize() routine currently returns [0,0,0] for zero
magnitude which propagates into STEP DIRECTION/_axis2_placement_3d; change
behavior to either (a) make normalize(vector) raise a clear ValueError on zero
magnitude (update function normalize in stepfg._geometry) or (b) keep normalize
but add explicit fallbacks at callers in stepfg._builder where
normalize(direction), normalize(zaxis), normalize(vertices[i] - vertices[0]) and
normalize(cross_product(...)) are used: detect zero magnitude and substitute a
well-defined default unit axis (e.g., [1,0,0] or compute a non-parallel axis) or
recompute a valid orthonormal, and add a unit test exercising normalization of a
zero vector to ensure the resolver path is exercised; pick one approach and
apply consistently across the referenced call sites and tests.

---

Nitpick comments:
In `@stepfg/_geometry.py`:
- Line 14: Replace the exact zero check on magnitude with an epsilon comparison
to avoid dividing by near-zero floats: instead of if magnitude == 0 use if
abs(magnitude) < EPS where EPS is a small constant (e.g. 1e-12 or
numpy.finfo(float).eps) defined near the top of the module; when the magnitude
is below EPS handle the near-zero vector_in the same way you currently handle
exact zeros (return a zero vector or skip normalization) to preserve numerical
stability. Ensure you reference the same symbols (magnitude, vector_in) and add
an import or constant definition for EPS if not already present.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bf43152a-6df1-47f2-b1b2-48a4a7c7c7b9

📥 Commits

Reviewing files that changed from the base of the PR and between 82b67b0 and 93b3258.

📒 Files selected for processing (1)
  • stepfg/_geometry.py

Comment thread stepfg/_geometry.py
Comment on lines +14 to +15
if magnitude == 0: # in some cases vector_in has zeros only
return [0 for _ in vector_in]
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Find all callers of normalize() to verify they handle zero vector returns

# Find all calls to normalize()
rg -n -B3 -A3 'normalize\(' --type=py -g '!test_*.py' -g '!*_test.py'

Repository: evvaletov/stepfg

Length of output: 2850


Fix zero-vector handling for normalize() results used as STEP directions

  • stepfg/_builder.py passes normalize(...) results directly into STEP DIRECTION and _axis2_placement_3d inputs (e.g., normalize(direction); normalize(zaxis) / normalize(vertices[*] - vertices[0]); and normalize(cross_product(...))), so a [0, 0, 0] return would propagate into emitted geometry.
  • The check if list(map(operator.add, normalize(zaxis), normalize(cp))) == [0, 0, 0]: only flips winding; it does not prevent emitting [0, 0, 0] direction vectors.

Handle zero magnitude either by making normalize() raise (or otherwise refuse), or by adding a well-defined fallback at these call sites, and add a test covering zero-vector normalization.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@stepfg/_geometry.py` around lines 14 - 15, The normalize() routine currently
returns [0,0,0] for zero magnitude which propagates into STEP
DIRECTION/_axis2_placement_3d; change behavior to either (a) make
normalize(vector) raise a clear ValueError on zero magnitude (update function
normalize in stepfg._geometry) or (b) keep normalize but add explicit fallbacks
at callers in stepfg._builder where normalize(direction), normalize(zaxis),
normalize(vertices[i] - vertices[0]) and normalize(cross_product(...)) are used:
detect zero magnitude and substitute a well-defined default unit axis (e.g.,
[1,0,0] or compute a non-parallel axis) or recompute a valid orthonormal, and
add a unit test exercising normalization of a zero vector to ensure the resolver
path is exercised; pick one approach and apply consistently across the
referenced call sites and tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant